<template>
  <view class="chat-page" @touchmove.stop.prevent="() => {}">
    <!-- 消息列表 -->
    <scroll-view class="chat-container" @touchmove.stop scroll-y  overflow-anchor :scroll-top="scrollViewTop" @scroll="onScroll" scroll-with-animation>
      <view
        v-for="(message, index) in messages"
        :key="index"
        :class="message.senderId === senderId ? 'my-message' : 'other-message'"
        @touchend="handleTouchEnd"
        @touchmove="handleTouchMove"
        :style="{ animation: message.animation }"
      >
		<view class="message-item" v-if="(((message.senderId==receiverId)&&(message.receiverId==senderId))||((message.senderId==senderId)&&(message.receiverId==receiverId)))">
			  <!--发送者-{{message.senderId}}接受者-{{message.receiverId}}-->
			  <view class="message-time" v-if="shouldShowTime(index)">{{ timeShow(message.timestamp) }}</view>
			  <view class="message-content-container">
			      <u-avatar
					class="avatar"
					mode="aspectFill"
					@click="goToPersonalInformation(message.senderId)"
			        :src="message.senderId === senderId ? myAvatar : otherAvatar"
			        @error="handleImageError(message.senderId)"
			      />
			    <view
			      class="message-content"
			      @touchstart="handleTouchStart($event, index)"
			      :class="{ highlight: selectedMessageIndex === index }"
			    >
			      <text>{{ message.content }}</text>
			    </view>
				<view v-if="message.unsent != null && message.unsent" class="unsent-container">
				        <view class="circle">
				            <text class="unsent">!</text>
				        </view>
				</view>
			  </view>
		</view>
      </view>
    </scroll-view>

    <!-- 自定义弹窗 -->
    <view v-if="showPopup" class="popup-background" @click="closePopup">
      <view class="popup" :style="popupStyle" @click.stop>
        <view class="popup-content">
          <button class="setting" @click="copyMessage">复制</button>
          <button class="setting" @click="deleteMessage">删除</button>
        </view>
      </view>
    </view>

    <!-- 输入框 -->
    <view class="input-area">
      <input
        v-model="inputMessage"
        @confirm="sendMessage"
        placeholder="请输入消息...10000字以内"
        maxlength="10000"
      />
      <button class="sent" @click="sendMessage">发送</button>
    </view>
  </view>
</template>

<script>
import data from "@/utils/data.js" 
import { mapState } from 'vuex';
export default {
  data() {
    return {
      senderId: "",
      receiverId: "",
      username: "",
	  myUsername:'自己的用户名',
      messages: [],
      inputMessage: "",
      myAvatar: "",
      otherAvatar: "",
	  token:null,
      fallbackAvatar: "https://your-backup-image-url.com/fallback.png",
      showPopup: false,
      selectedMessageIndex: null,
      popupStyle: {
        top: '0px',
        left: '0px',
      },
      longPressTimer: null,
      isMoving: false,
      isTouching: false,
	  scrollViewTop: 0, // 当前滚动位置
	  oldScrollTop: 0,
	  target: null // 实时变化的scroll对象
    };
  },
  computed: {
  	    ...mapState(["isMessagesListChange"]), // 映射 Vuex 状态
  	 },
  watch:{
  	isMessagesListChange(newVal, oldVal) {
		this.scrollToBottom();
			this.getMessagesList();
			var usersList = uni.getStorageSync('usersList') || [];
			var userIndex = usersList.findIndex(existingUser => existingUser.uid == this.receiverId);
			if (userIndex !== -1) { // 如果发消息的人已经在本地有记录了
			    // 更新用户信息
			    usersList[userIndex].hasNew = false;
			    // 将用户移到最前面
			    var user = usersList.splice(userIndex, 1)[0]; // 删除用户并获取该用户
			    usersList.unshift(user); // 将用户添加到最前面
			}
			uni.setStorageSync('usersList', usersList);
			this.$store.commit('changeUsersList', usersList);
  	}
  },
  onLoad(param) {
    this.receiverId = param.uid;
    this.username = param.username;
	var uid=uni.getStorageSync("UID")
    this.senderId = uid;
	this.token=uni.getStorageSync('token')
    uni.setNavigationBarTitle({
      title: param.username,
    });
  },
  onShow() {
    uni.setNavigationBarTitle({
      title: this.username,
    });
	this.getMessagesList();
	this.getUsername()
	this.myAvatar=uni.getStorageSync('userAvatar'+this.senderId);//
	this.otherAvatar=uni.getStorageSync('userAvatar'+this.receiverId)//获取本地头像
	this.getUserAvatar(this.receiverId)//获取后台头像
  },
  onHide() {
  	this.$store.commit('changeUsersList',null)
  	this.$store.commit('changeMessagesList',null)
  },
  mounted() {
      setInterval(this.$store.commit('changeMessagesList',this.messages), 60000); // 每分钟更新
    },
    beforeDestroy() {
      clearInterval(this.interval); // 清除定时器
    },
  methods: {
	getUsername(){
			uni.request({
				url:this.baseUrl+"/getUsername",
				method:"POST",
				data:{
					data:{
						userId:Number(this.receiverId)
					},
					msgType:'getUsername'
				},
				header: {
					'Content-Type': 'application/json',// 如果需要以JSON格式发送数据
					'token':this.token,
					'uid':this.senderId
				},
				success: (res) => {
					if(res.data.code==1){
						this.username=res.data.data.username
						uni.setNavigationBarTitle({
						  title: this.username,
						});
						var usersList = uni.getStorageSync('usersList') || [];
						var userIndex = usersList.findIndex(existingUser =>( existingUser.uid == this.receiverId));
						if (userIndex !== -1) {
						    // 更新用户信息
						    usersList[userIndex].username=this.username;
						}
						uni.setStorageSync('usersList', usersList);
						this.$store.commit('changeUsersList',usersList)
					}
				}
			})
	},
	  shouldShowTime(index) {
	      if (index === 0) return true; // 第一条消息始终显示时间
	      const currentMessage = this.messages[index];
	      const previousMessage = this.messages[index - 1];
	      // 比较当前消息与上一条消息的时间戳是否相同
	      return this.timeShow(currentMessage.timestamp) !== this.timeShow(previousMessage.timestamp);
	    },
	  timeShow(timestamp){
		 const now = new Date();
		    const messageTime = new Date(timestamp);
		    const diffInSeconds = Math.floor((now - messageTime) / 1000);
		    
		    if (diffInSeconds < 60) {
		        return '刚刚';
		    } else if (diffInSeconds < 3600) {
		        const minutes = Math.floor(diffInSeconds / 60);
		        return `${minutes}分钟前`;
		    } else if (diffInSeconds < 86400) {
		        const hours = Math.floor(diffInSeconds / 3600);
		        return `${hours}小时前`;
		    } else {
		        const year = messageTime.getFullYear();
		                const month = String(messageTime.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
		                const day = String(messageTime.getDate()).padStart(2, '0');
		                const hour = String(messageTime.getHours()).padStart(2, '0');
		                const minute = String(messageTime.getMinutes()).padStart(2, '0');
		                
		                return `${year}-${month}-${day} ${hour}:${minute}`;
		    }
	  },
	  getUserAvatar(uid){
		  uni.request({
		      url: this.baseUrl+'/getUserAvatar',
		      method: 'POST',
		      data: {
		  		data:{
		  			userId:Number(uid)
		  		},
		  		msgType:'getUserAvatar'
		      },
		      header: {
		  		'Content-Type': 'application/json',
		  		'token':this.token,
		  		'uid':this.senderId
		      },
		      success: (res) => {
		  		if(res.data.code==1){
		  			const userAvatar=res.data.data.imgType+'base64,'+res.data.data.userAvatar;
					const oldAvatar=uni.getStorageSync('userAvatar'+this.receiverId)
					if(oldAvatar!=userAvatar){//进入页面请求一次用户头像，发现用户头像发生改变，就修改本地用户头像
					this.otherAvatar=userAvatar
					console.log("头像发生变化")
						uni.setStorageSync('userAvatar'+this.receiverId,this.otherAvatar)
						var usersList=uni.getStorageSync('usersList')
						this.$store.commit('changeUsersList',usersList)
					}
		  		}else{
					// 该用户服务器没有设置头像,启用默认头像
					
				}
		      },
		      fail: (err) => {
		  		console.error('请求失败:', err);
		      }
		  });
	  },
	  getMessagesList(){
		// 从本地存储中获取所有消息列表
		var allMessagesList = uni.getStorageSync('messagesList') || [];
		this.messages = allMessagesList; 
		this.scrollToBottom();
	  },
    goToPersonalInformation(senderId) {
		var uid;
		var username
		if(senderId==this.senderId){
			username=uni.getStorageSync('username')
		}else{
			username=this.username
		}
      uni.navigateTo({
        url: "/pages/personalInformation/personalInformation?uid=" + senderId+"&unAllowChat=true&username="+username
      });
    },
    handleTouchStart(event, index) {
      this.isMoving = false;
      this.isTouching = true;
      this.longPressTimer = setTimeout(() => {
        if (!this.isMoving) {
		plus.device.vibrate(100)
          this.showSetting(index);
        }
      }, 500); // 500ms 为长按时间
    },
    handleTouchMove() {
      this.isMoving = true; // 用户正在移动
    },
    handleTouchEnd() {
      clearTimeout(this.longPressTimer); // 清除定时器
      this.isMoving = false; // 重置移动状态
      this.isTouching = false; // 重置触摸状态
    },
    showSetting(index) {
      this.selectedMessageIndex = index;
      this.showPopup = true;
    },
    closePopup() {
      this.showPopup = false;
      this.selectedMessageIndex = null;
    },
    copyMessage() {
      const message = this.messages[this.selectedMessageIndex].content;
      uni.setClipboardData({
        data: message,
        success: () => {
          uni.showToast({
            title: "消息已复制",
            icon: "none",
            duration: 300,
          });
        },
      });
      this.closePopup();
    },
    deleteMessage() {
      const index = this.selectedMessageIndex;
      this.messages[index].animation = 'fadeOut 0.5s forwards'; // 设置删除动画
      setTimeout(() => {
        this.messages.splice(index, 1); // 删除消息
		uni.setStorageSync('messagesList',this.messages)
        this.closePopup();
      }, 500); // 与动画持续时间一致
      uni.showToast({
        title: "消息已删除",
        icon: "none",
        duration: 300,
      });
    },
    sendMessage() {
      if (this.inputMessage.trim()) {
        const timestamp = this.formatDate(new Date());
        var message = {
          senderId: this.senderId,
          receiverId: this.receiverId,
          content: this.inputMessage,
          createdAt: timestamp,
        };
       var res= this.$websocket.sendChatMessage(message);
        
        // 在空消息前插入新消息
		var newMessage= {
			  senderId: this.senderId,
			  receiverId: this.receiverId,
			  content: this.inputMessage,
			  timestamp,
			  animation: 'fadeIn 0.5s forwards' ,// 设置增加动画
			  unsent:true
			}
		if(res){
			newMessage.unsent=false;
		}else{
			uni.showToast({ title: '发送失败，已断开连接', icon: 'none', duration: 1000 });
		}
		var usersList = uni.getStorageSync('usersList') || [];
		var userIndex = usersList.findIndex(existingUser => existingUser.uid == message.receiverId);
		if (userIndex !== -1) { // 如果发消息的人已经在本地有记录了
		    // 更新用户信息
		    usersList[userIndex].content = message.content;
		    usersList[userIndex].time = message.createdAt;
		    // 将用户移到最前面
		    var user = usersList.splice(userIndex, 1)[0]; // 删除用户并获取该用户
		    usersList.unshift(user); // 将用户添加到最前面
		} else {
		    var newUser = {
		        uid: String(message.receiverId),
				toUid:String(message.senderId),
		        avatar: this.otherAvatar,
		        username:this.username,
		        time: message.createdAt,
		        content: message.content,
		        offsetX: 0,
		        isTop: false,
		        hasNew: false,
		        isDeleting: false,
		    };
		    // 使用 unshift 将 newUser 插入到最前面
		    usersList.unshift(newUser);
		}
		this.messages.push(newMessage);
		this.scrollToBottom();
		uni.setStorageSync('usersList',usersList)
		this.$store.commit('changeUsersList',usersList)
        uni.setStorageSync('messagesList',this.messages)
        this.inputMessage = ""; // 清空输入框
      }
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    handleImageError(sender) {
      return (event) => {
        event.target.src = this.fallbackAvatar;
        console.log(`头像加载失败，使用备用头像：${sender}`);
      };
    },
	scrollToBottom() {
	    this.scrollViewTop = this.oldScrollTop;
	    this.$nextTick(() => {
	        this.scrollViewTop = (this.messages.length) * 1000+100; // 这里的 1000 是假设每个日志项的高度
	    });
	},
	scrollToTop() {
	    this.scrollViewTop = this.oldScrollTop;
	    if (this.scrollViewTop == 0) {
	        uni.showToast({ title: "已经在最顶部了", icon: "none", duration: 1000 });
	        return;
	    }
	    this.$nextTick(() => {
	        this.scrollViewTop = 0;
	    });
	},
	onScroll(event) {
	    // 计算当前滚动位置
	    const { scrollTop, scrollHeight, clientHeight } = event.target;
	    this.oldScrollTop = scrollTop;
	},
	showScroll() {
	    uni.showToast({
	        title: "滑动位置：" + this.oldScrollTop,
	        icon: "none",
	        duration: 1000
	    });
	},
  },
};
</script>

<style>
.chat-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.chat-container {
  flex: 1;
  overflow-y: scroll;
}

.message-time {
  font-size: 24rpx;
  color: #888;
  margin-bottom: 10rpx;
  text-align: center;
}

.message-item {
  display: flex;
  flex-direction: column;
  padding: 15rpx 0;
  animation: fadeIn 0.5s forwards; /* 默认增加动画 */
}

.message-content-container {
  display: flex;
  align-items: center;
}

.my-message .message-content-container {
  flex-direction: row-reverse;
}

.avatar {
  width: 99rpx;
  height: 99rpx;
  border-radius: 50%;
  overflow: hidden;
  margin: 0 20rpx;
  background-color: #e0e0e0;
  border-radius: 50%;
  border: 6rpx solid #dddddd;
}


.message-content {
  max-width: 70%;
  padding: 20rpx;
  border-radius: 10rpx;
  background-color: #fff;
  box-shadow: 0 0 5rpx rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
  word-wrap: break-word;
  overflow-wrap: break-word;
  white-space: normal;
}

.my-message .message-content {
  background-color: #daf8cb;
}

.input-area {
  display: flex;
  padding: 30rpx;
  background-color: #fff;
  border-top: 1rpx solid #ddd;
  box-shadow: 0 -1rpx 5rpx rgba(0, 0, 0, 0.1);
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeOut {
  from {
    opacity: 1;
    transform: translateY(0);
  }
  to {
    opacity: 0;
    transform: translateY(10px);
  }
}

@keyframes glow {
  0% {
    box-shadow: 0 0 10rpx rgba(0, 255, 255, 0.6), 0 0 20rpx rgba(255, 0, 255, 0.4);
    border-color: #00ffff;
  }
  25% {
    box-shadow: 5rpx 5rpx 15rpx rgba(0, 255, 255, 0.8), 5rpx 5rpx 30rpx rgba(255, 0, 255, 0.5);
    border-color: #ff00ff;
  }
  50% {
    box-shadow: 0 0 20rpx rgba(255, 0, 255, 0.6), 0 0 25rpx rgba(0, 255, 255, 0.4);
    border-color: #00ffff;
  }
  75% {
    box-shadow: -5rpx -5rpx 15rpx rgba(0, 255, 255, 0.8), -5rpx -5rpx 30rpx rgba(255, 0, 255, 0.5);
    border-color: #ff00ff;
  }
  100% {
    box-shadow: 0 0 10rpx rgba(0, 255, 255, 0.6), 0 0 20rpx rgba(255, 0, 255, 0.4);
    border-color: #00ffff;
  }
}

.message-content.highlight {
  transform: scale(1.05);
  animation: glow 2s infinite;
  border: 5rpx solid #ffd700;
}

input {
  flex: 1;
  height: 80rpx;
  border: 1rpx solid #ddd;
  border-radius: 25rpx;
  outline: none;
  padding: 0 10rpx;
  font-size: 28rpx;
  margin-right: 10rpx;
  transition: border-color 0.3s;
}

.sent {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 80rpx;
  padding: 0 20rpx;
  background: linear-gradient(45deg, #007aff, #0056b3);
  color: white;
  width: 150rpx;
  border: none;
  border-radius: 40rpx;
  margin-left: 10rpx;
  font-size: 28rpx;
  line-height: 80rpx;
  transition: background-color 0.3s, box-shadow 0.3s;
  box-shadow: 0 4rpx 15rpx rgba(0, 122, 255, 0.5);
}


.popup-background {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  background: rgba(255, 255, 255, 0.0);
  align-items: center;
  z-index: 999;
}

.popup {
  border: 1rpx solid #ddd;
  border-radius: 10rpx;
  box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.2);
  width: 250rpx;
}

.setting {
    font-size: 30rpx; /* 保持大小不变 */
    width: 125rpx; 
    font-weight: bold; /* 加粗字体 */
}

.popup-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-message {
  height: 120rpx; /* 设置占位符的高度 */
}
.unsent-container {
    display: flex;
	margin: 0 20rpx;
    align-items: center; /* 垂直居中对齐 */
}

.circle {
    width: 40rpx; /* 圆的直径 */
    height: 40rpx; /* 圆的直径 */
    border-radius: 50%; /* 使其成为圆形 */
    background-color: red; /* 圆的颜色 */
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
}

.unsent {
    color: white; /* 感叹号的颜色，可以根据需要调整 */
    font-size: 40rpx; /* 感叹号的字体大小 */
    font-weight: bold; /* 加粗字体 */
}
</style>
